package com.itheima.health.interceptor;


import com.itheima.health.constant.AuthenticationConstant;
import com.itheima.health.context.BaseContext;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginMobileInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        log.info("移动端拦截器拦截请求:{}", request.getRequestURL());
        if (handler instanceof HandlerMethod){
            HttpSession session = request.getSession();
            Member memberUser = (Member) session.getAttribute(AuthenticationConstant.MOBILE_USER);
            System.out.println(memberUser);
            if (null == memberUser ){
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
            }
            Integer id = memberUser.getId();
            BaseContext.setCurrentId(id);
        }
        return true;
    }

    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}